package com.lerays.spider.sougou.handler;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;

import org.lionsoul.websnail.json.JSONObject;

import com.lerays.spider.sougou.SpiderHttpServer;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * default http request handler. <br />
 * 
 * @author chenxin<chenxin619315@gmail.com>
 */
public class ControlRequestHandler implements HttpHandler
{
	private SpiderHttpServer httpServer = null;
	
	public ControlRequestHandler( SpiderHttpServer httpServer )
	{
		this.setHttpServer(httpServer);
	}

	@Override
	public void handle(HttpExchange e) throws IOException 
	{	
		JSONObject json = new JSONObject();
		
		String path = e.getRequestURI().getPath();
		if ( path.indexOf("/pause") > -1 )				//pause the spider
		{
			httpServer.getsougouSpider().pause();
			json.put("opt", "pause");
			json.put("status", true);
		}
		else if ( path.indexOf("/resume") > -1 )		//resume the spider
		{
			httpServer.getsougouSpider().resume();
			json.put("opt", "resume");
			json.put("status", true);
		}
		else if ( path.indexOf("/work") > -1 )			//make the spider work
		{
			httpServer.getsougouSpider().leadSourceInTodo();
			httpServer.getsougouSpider().resume();
			json.put("opt", "work");
			json.put("status", true);
		}
		else if ( path.indexOf("/reload") > -1 )		//reload source
		{
			json.put("opt", "reload");
			boolean ret = true;
			try {
				httpServer.getsougouSpider().loadSourceFromDb();
			} catch (SQLException e1) {
				ret = false;
			}			
			json.put("status", ret);
		}
		else if ( path.indexOf("/clear") > -1 )			//clear the todo
		{
			httpServer.getsougouSpider().getSpider().getTodoHandler().clear();
			httpServer.getsougouSpider().setFailedTaskCount(0);
			json.put("opt", "clear");
			json.put("status", true);
		}
		else
		{
			json.put("err", "Invalid control operation");
		}
		
		//send the http response
		String ret = json.toString();
		e.sendResponseHeaders(200, ret.length());
		OutputStream os = e.getResponseBody();
		os.write(ret.getBytes());
		os.close();
		e.close();
	}

	public SpiderHttpServer getHttpServer() 
	{
		return httpServer;
	}

	public void setHttpServer(SpiderHttpServer httpServer) 
	{
		this.httpServer = httpServer;
	}
}
